package com.bit.bitstudy;

import java.io.*;
import java.util.*;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.json.*;

import android.os.*;
import android.app.Activity;
import android.util.*;
import android.view.*;
import android.widget.*;

public class ActivityChat extends Activity {
	
	private ArrayList<ChatMsg> arData;
	private ChatMsgAdapter adapter;
	private EditText mEditText;
	protected String mName = "tester";
	protected int mLastID = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
		
		ListView listView = (ListView)findViewById(R.id.list_chat);
		mEditText = (EditText)findViewById(R.id.txt_msg);
		
		arData = new ArrayList<ChatMsg>();
		adapter = new ChatMsgAdapter(this, R.layout.chatmsg, arData);
		listView.setAdapter(adapter);
		
		mChatListHandler.sendEmptyMessage(0);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_chat, menu);
		return true;
	}
	
	public void onClick(View v) {
		String msg = mEditText.getText().toString();
		String url = "http://godling2.cafe24.com/chat/index.php/room/cmsg/name/"+mName+"/data/"+msg;
		Log.e("onClick", url);
		mEditText.setText("");
		DownThread thread = new DownThread(url, mSResHandler);
		thread.start();
	}
	
	ResponseHandler<String> mSResHandler = new ResponseHandler<String>() {

		@Override
		public String handleResponse(HttpResponse response) {
			mChatListHandler.sendEmptyMessage(0);
			
			return "";
		}
		
	};
	
	Handler mChatListHandler = new Handler() {
		
		public void handleMessage(Message msg) {
			mChatListHandler.sendEmptyMessageDelayed(0, 3000);

			String url = "http://godling2.cafe24.com/chat/index.php/room/cmsgs/id/"+mLastID+"/format/json";
			DownThread thread = new DownThread(url, mResHandler);
			thread.start();
		}
		
	};
	
	class DownThread extends Thread {
		String mAddr;
		ResponseHandler<String> mHandler;
		DownThread(String addr, ResponseHandler<String> handler) {
			mAddr = addr;
			mHandler = handler;
		}
		
		public void run() {
			HttpGet get = new HttpGet(mAddr);
			DefaultHttpClient client = new DefaultHttpClient();
			try {
				client.execute(get, mHandler);
			}
			catch (Exception e) {;}
		}
	}
	
	ResponseHandler<String> mResHandler = new ResponseHandler<String>() {

		@Override
		public String handleResponse(HttpResponse response) {
			StringBuilder json = new StringBuilder();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						response.getEntity().getContent()));
				for (;;) {
					String line = br.readLine();
					if (line == null) break;
					json.append(line);
				}
				br.close();
				
				Message message = mAfterDown.obtainMessage();
				message.obj = json.toString();
				mAfterDown.sendMessage(message);
			}
			catch (Exception e) {;}
			
			return json.toString();
		}
		
	};
	
	
	Handler mAfterDown = new Handler() {
		
		public void handleMessage(Message msg) {
			
			String json = (String)msg.obj;
			
			try {
				JSONArray ja = new JSONArray(json);
				for (int i = 0; i < ja.length(); i++) {
					JSONObject chatmsg = ja.getJSONObject(i);
					mLastID = Integer.parseInt(chatmsg.getString("id")) + 1;
					String name = chatmsg.getString("user_nicename");
					String data = chatmsg.getString("user_msg");
					if ( name.equals(mName) ) {
						arData.add(new ChatMsg("", data));
					} else {
						arData.add(new ChatMsg(data, ""));
					}
				}
				adapter.notifyDataSetChanged();
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
	};

}
